<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.roleName" placeholder="角色名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        {{ $t('table.search') }}
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        {{ $t('table.add') }}
      </el-button>
    </div>
   <!--表格内容-->
   <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="roleId" 
      sortable="custom" align="center" width="80" :class-name="getSortClass('bookId')">
        <template slot-scope="{row}">
          <span>{{ row.roleId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色名" prop="roleName" 
      sortable="custom" align="center" width="80" >
        <template slot-scope="{row}">
          <span>{{ row.roleName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色描述" prop="description" 
      sortable="custom" align="center" width="80" >
        <template slot-scope="{row}">
          <span>{{ row.description }}</span>
        </template>
      </el-table-column>
      <!--表格内部按钮-->
      <el-table-column :label="$t('table.actions')" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            {{ $t('table.edit') }}
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            {{ $t('table.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
     <!--修改的表单-->
     <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" @before-close="handleDialogBeforeClose">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="ID">
          <el-input v-model="temp.roleId" :autosize="{ minRows: 2, maxRows: 4}" 
           retype="text" readonly=""/>
        </el-form-item>
        <el-form-item label="角色名称">
          <el-input v-model="temp.roleName"  type="text" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="temp.description"  type="text" placeholder="请输入角色描述" />
        </el-form-item>
        <el-form-item label="权限">
          <div style="margin: 15px 0;"></div>
          <el-checkbox-group v-model="checkedPermission" @change="handleCheckedPermissionsChange">
            <el-checkbox v-for="item in permissionList" :key="item.permissionId" :label="item.permissionId" :value="item.permissionId">{{item.permissionName}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false;checkedPermission = []">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">{{ $t('table.confirm') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { findByPage, deleteRole, addRole, updateRole} from '@/api/role'
import { findAllPermissionList, findCheckedPermissionList} from '@/api/permission'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
  },
  data() {
    return {
      checkAll: false,
      //选中的权限（该角色拥有的权限）
      checkedPermission:null,
      //所有权限
      permissionList: null,
      isIndeterminate: true,
      permissionListLoading:true,
      checkedPermissionListLoading:true,

      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        roleName:undefined
      },
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      showReviewer: false,
      temp: {//修改信息
        roleId: undefined,
        roleName: '',
        description:undefined
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        roleName: [{ required: true, message: '角色名不能为空', trigger: 'change' }]
      },
      downloadLoading: false,
    }
  },
  created() {
    this.getPermissionList();
    this.getList();
  },
  methods: {
     //查询所有权限
     getPermissionList(){
            this.permissionListLoading = true;
            findAllPermissionList().then(response => {
            this.permissionList=response.data
            console.log("查询所有权限"+this.permissionList);
            this.permissionListLoading=false;
            })
      },
    handleDialogBeforeClose(done) {
      this.checkedPermission = [];
      done(); // 调用 done 函数来继续关闭对话框的流程，如果不调用，对话框将不会关闭
    },
    handleCheckedPermissionsChange(value) {
        let checkedCount = value.length;
        this.checkAll = checkedCount === this.permissionList.length;
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.permissionList.length;
    },
    getList() {
      this.listLoading = true;
        console.log("哈哈"+this.listQuery)
        findByPage(this.listQuery).then(response => {
          this.list = response.data.list
          console.log(response.data.list)
          this.total = response.data.total
          console.log( response.data.list)
          this.listLoading = false
         })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        status: 'published',
        type: ''
      }
    },
    handleCreate() {
      // 新增代码：调用查询所有权限的方法
      this.getPermissionList(),
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true,
      
      
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    //添加
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        //临时数据   temp内容拷贝到tempData
        const tempData = Object.assign({}, this.temp)
          // 将选中的权限数据添加到要发送给后端的对象中
          tempData.permissionIdList = this.checkedPermission;
        //判断验证是否通过
        if (valid) {     
          addRole(tempData).then(response => {
            //把当前内容添加到 集合中
          // this.list.unshift(this.temp)
          this.getList();
           //设置是否被不通过
           this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row); // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp);
      this.dialogStatus = 'update';
      this.dialogFormVisible = true;
      console.log("handleUpdate"+row.roleId)
      // 新增代码，调用查询角色权限的方法
      findCheckedPermissionList (row.roleId).then(response  => {
        this.checkedPermission=response.data;
        console.log('已成功获取角色权限信息，可进行后续展示等操作'+this.checkedPermission);
      }).catch((error) => {
        // 若获取权限数据出现错误的处理逻辑
        console.error('获取角色权限信息失败：', error);
        this.$message.error('获取角色权限失败，请稍后再试');
      });
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
   //修改
   updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          //临时数据   temp内容拷贝到tempData
          const tempData = Object.assign({}, this.temp)
          // 将选中的权限数据添加到要发送给后端的对象中
          tempData.permissionIdList = this.checkedPermission;
          updateRole(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            //替换
           // this.list.splice(index, 1, this.temp)
           this.getList();
            this.dialogFormVisible = false
            this.checkedPermission = [];
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      deleteRole(row.roleId).then(() => {
            this.getList();
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          })
    },
    handleFetchPv(pv) {
      
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
